#!/bin/bash

PLATFORM=$1
JDGIT_HOME=$2
TARGET_BRANCH=$3
ANDROID_GIT='jd-android-phone-r4'
module_exceed_limit='false'
message=""
currentPath=`pwd`
echo "currentPath = $currentPath"
if [ -e out ]; then
	rm -fr out
fi
if [ -e out.zip ]; then
  rm out.zip
fi
mkdir out

# init & fetch android git
if [ $PLATFORM == 'android' ]; then
  if [ -d $JDGIT_HOME/$ANDROID_GIT ]; then
    cd $JDGIT_HOME/$ANDROID_GIT
    echo ">>>>>> fetch latest Android GIT"
    git checkout -- .
    git gc
    git fetch origin $TARGET_BRANCH || git fetch origin $TARGET_BRANCH || git fetch origin $TARGET_BRANCH || doErrorExit
    if [[ "$?" != "0" ]]; then
      echo ">>>>>> GIT fetch Failed!!! ...."
      exit 1
    fi
    echo ">>>>>> GIT fetch ok!!! ...."
    git checkout origin/$TARGET_BRANCH
    cd -
  else
    echo ">>>>>> not find android git, exit!"
    exit 1
  fi
fi

if [ $PLATFORM == 'android' ]; then
    resPath=$JDGIT_HOME/$ANDROID_GIT/AndroidJD-Phone/res/
    cd $JDGIT_HOME/$ANDROID_GIT/AndroidJD-Phone/assets/jdreact
    for file in $(ls); do
	    if [ $file == 'JDReactCommon' ]; then
		    continue;
	    fi
      if [ $file == 'out.zip' ]; then
        continue;
      fi
	    outFile=${currentPath}/out/${file}.csv
	    bash ${currentPath}/scan_module_as_csv.sh -p ${resPath} -m ${file} -e 'caoxu6@jd.com' > $outFile
	    if [ $? == 1 ]; then
		    echo "module:${file} exceed limit, see details in $outFile"
        module_exceed_limit='true'
	    fi
    done
    #send mail to jdreact team
    if [ $module_exceed_limit == 'true' ]; then
      cd ${currentPath}/out
      zip -r out.zip *
      subject="The overall statistical results of modules which exceeds the standard."
      #message_warning="<h1 style=\"color:red\">Warning</h1>";
      message="please check the attached files for details!";
      python ${currentPath}/auto-send-mail-new.py -s "$subject" -m "$message" -e "sstp-xplatform@jd.com";
    fi
fi

cd - > /dev/null